﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Security.Policy;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.UI.WebControls;
using Kojarskiy.Core;
using log4net;
using log4net.Config;
using Microsoft.Data.OData;

namespace Kojarskiy
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class KojarskiyApplication : HttpApplication
    {
        public enum ErrorType
        {
            Info,
            Warning,
            Fatal
        }

        public static Message Message 
        {
            get
            {
                if (HttpContext.Current.Session["GlobalMessage"] == null) HttpContext.Current.Session["GlobalMessage"] = new Message(MessageType.Information, "");

                var message = (Message)HttpContext.Current.Session["GlobalMessage"];

                if ((DateTime.Now -message.Publication) > new TimeSpan(0, 0, 0, 5))
                    HttpContext.Current.Session["GlobalMessage"] = new Message(MessageType.Information, "");

                return (Message)HttpContext.Current.Session["GlobalMessage"];
            }
            set
            {
                HttpContext.Current.Session["GlobalMessage"] = value;
            }
        }

        private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public static void Log(ErrorType type, string message, string description)
        {
            switch (type)
            {
                case ErrorType.Info:
                    Logger.Info("<div class = \"bg-info\">" + message + " | " + description + "</div>");
                    break;
                case ErrorType.Warning:
                    Logger.Warn("<div class = \"bg-warning\">" + message + " | " + description + "</div>");
                    break;
                case ErrorType.Fatal:
                    Logger.Fatal("<div class = \"bg-danger\">" + message + " | " + description + "</div>");
                    break;
            }
            Message = new Message(MessageType.Exception, message);
        }

        protected void Application_Start()
        {
            XmlConfigurator.Configure();

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }


        protected void Application_Error(object sender, EventArgs e)
        {
            if (Server != null)
            {
                Exception ex = Server.GetLastError();

                if (Response.StatusCode != 404)
                {
                    Log(ErrorType.Fatal, ex.Message, ex.StackTrace);
                    Response.Redirect("~/");
                }
            }
        }

        protected void Application_BeginRequest()
        {
            string acceptEncoding = Request.Headers["Accept-Encoding"];
            Stream prevUncompressedStream = Response.Filter;

            if (String.IsNullOrEmpty(acceptEncoding)) return;

            acceptEncoding = acceptEncoding.ToLower();

            if (acceptEncoding.Contains("gzip"))
            {
                Response.Filter = new GZipStream(prevUncompressedStream, CompressionMode.Compress);
                Response.AppendHeader("Content-Encoding", "gzip");
            }
            else if (acceptEncoding.Contains("deflate"))
            {
                Response.Filter = new DeflateStream(prevUncompressedStream, CompressionMode.Compress);
                Response.AppendHeader("Content-Encoding", "deflate");
            }
        }
    }
}